package com.situ.mvc.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.situ.mvc.dao.IUserDao;
import com.situ.mvc.entity.User;
import com.situ.mvc.util.UserJDBCUtil;

public class UserDaoImpl implements IUserDao {

	@Override
	public boolean checkName(String name) {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		boolean result = false;
		try {
			connection = UserJDBCUtil.getConnection();
			String sql = "select * from user where name=?;";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, name);
			resultSet = preparedStatement.executeQuery();
			if (resultSet.next()) {
				result = true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public User login(String name, String password) {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		try {
			connection = UserJDBCUtil.getConnection();
			String sql = "select id,name,password,email,department_id,age from user where name = ? and password = ?;";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, name);
			preparedStatement.setString(2, password);
			resultSet = preparedStatement.executeQuery();
			while (resultSet.next()) {
				int id = resultSet.getInt("id");
				String userName = resultSet.getString("name");
				String userPassword = resultSet.getString("password");
				String email = resultSet.getString("email");
				int department_id = resultSet.getInt("department_id");
				int age = resultSet.getInt("age");
				User user = new User(id, userName, userPassword, email, department_id, age);
				return user;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

}
